A UNIX timestamp is defined as the several numbers of seconds between a particular date and the Epoch i.e January 1, 1970 at UTC.
In this tutorial, we will see some methods by which we can convert a UNIX timestamp to DateTime in Python.
Table of Contents
Using fromtimestamp()
Function
DateTime module in python is used to deal with the date and time-related problems in python.
One of the functions in this module is the fromtimestamp()
function. This function returns the time that is expressed as seconds i.e UNIX timestamp.
Example 1:
1 2 3 4 5 6 |
from datetime import datetime timestamp = 1564728223 unix_val = datetime.fromtimestamp(timestamp) print("dateAndtime:",unix_val) |
Output:
Here, we first import the datetime
class from the datetime module. Then we store the UNIX value object in a variable. After that, we use the datetime.fromtimestamp()
function that will get us the time and date. Finally, we print the unix_val
variable.
To get the current timestamp, we use the now()
function from the datetime module.
1 2 3 4 5 6 |
from datetime import datetime current = datetime.now() timestamp = datetime.timestamp(current) print("current timestamp =", timestamp) |
Output:
To convert this again to DateTime, we use the same code from example 1.
Using strftime()
Function
Another function in the datetime module is the strftime()
function. This function helps in returning the DateTime in a specific form. To convert the date and time objects to their string representation, this function is generally used.
Example:
1 2 3 4 5 6 |
from datetime import datetime timestamp = 1564728223 unix_conversion = datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S') print("Converted date and time:", unix_conversion) |
Output:
In the above code, %d, %m, %Y, %H, %M and %S are called format codes which represent days, month, year, hour, minutes, and seconds respectively. In this code also, fromtimestamp()
is used to return the time that is expressing in the UNIX timestamp.
Using to_datetime() Function
This function comes under the Pandas
library in python. Pandas
is one of the most common libraries in python. This library helps in manipulating and analyze data and is widely used in the field of data science.
The to_datatime()
of the Pandas
library helps in converting a Unix timestamp to DateTime in Python.
Example:
1 2 3 4 5 6 |
import pandas timestamp = 1564728223 unix_conversion=pandas.to_datetime(timestamp ,unit='s') print(str(unix_conversion)) |
Output:
In this method, we first start by importing the Pandas
which is pre-installed in python. Then we make a variable ‘timestamp’ to store the UNIX timestamp that has to converted. After that, we use the to_datetime
function. Note that, in the argument of the to_datetime
function, we have mentioned the unit equal to ‘s’. The unit variable represents the unit of the UNIX timestamp i.e seconds.
That’s all about how to convert UNIX timestamp to DateTime in Python.